<template>
  <!-- 原模板内容保持不变 -->
  <div class="room-type-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>房间类型管理</span>
          <el-button type="primary" @click="openDialog">添加房间类型</el-button>
          <el-dialog
            v-model="dialogVisible"
            :title="isEditing ? '编辑房间类型' : '添加房间类型'"
            width="500px"
          >
            <el-form :model="form" label-width="auto" style="max-width: 600px">
              <el-form-item label="类型ID" prop="typeId">
                <el-input v-model="form.typeId" placeholder="请输入类型ID" />
              </el-form-item>
              <el-form-item label="类型名称" prop="typeName">
                <el-input
                  v-model="form.typeName"
                  placeholder="请输入类型名称"
                />
              </el-form-item>
              <el-form-item label="床型" prop="bedType">
                <el-input v-model="form.bedType" placeholder="请输入床型" />
              </el-form-item>
              <el-form-item label="面积" prop="area">
                <el-input v-model="form.area" placeholder="请输入面积" />
              </el-form-item>
              <el-form-item label="设施" prop="facilities">
                <el-input v-model="form.facilities" placeholder="请输入设施" />
              </el-form-item>
              <el-form-item label="基础价格" prop="basePrice">
                <el-input
                  v-model="form.basePrice"
                  type="number"
                  placeholder="请输入基础价格"
                />
              </el-form-item>
            </el-form>

            <!-- 弹框底部操作按钮 -->
            <template #footer>
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">{{
                isEditing ? "保存修改" : "提交"
              }}</el-button>
            </template>
          </el-dialog>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="typeId" label="类型ID" width="100" />
        <el-table-column prop="typeName" label="类型名称" width="180" />
        <el-table-column prop="bedType" label="床型" width="240" />
        <el-table-column prop="area" label="面积(㎡)" width="130" />
        <el-table-column prop="facilities" label="设施" min-width="200" />
        <el-table-column prop="basePrice" label="基础价格" width="130">
          <template #default="scope">
            <span>¥{{ scope.row.basePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { RoomType } from "@/api/room";
import {
  getRoomTypeList,
  updateRoomType,
  createRoomType,
  deleteRoomType
} from "@/api/room";

defineOptions({
  name: "RoomType"
});

const tableData = ref<RoomType[]>([]);
const loading = ref(true);
const dialogVisible = ref(false);
const isEditing = ref(false); // 区分“新增”还是“编辑”
const editingOriginalId = ref(null);
const form = ref<RoomType>({
  typeId: null,
  typeName: "",
  bedType: "",
  area: null,
  facilities: "",
  basePrice: null
});

const fetchRoomTypes = async () => {
  try {
    const data = await getRoomTypeList();
    console.log("获取房间类型列表", data);
    if (data.code === 200) {
      tableData.value = data.data;
    } else {
      ElMessage.error(data.msg || "获取房间类型列表失败");
    }
  } catch (error) {
    ElMessage.error("获取房间类型列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchRoomTypes();
});

const openDialog = () => {
  isEditing.value = false; // 进入新增模式
  form.value = {
    typeId: null,
    typeName: "",
    bedType: "",
    area: null,
    facilities: "",
    basePrice: null
  }; // 清空表单
  dialogVisible.value = true;
};

const handleAdd = () => {
  tableData.value.push({ ...form.value });
  console.log("当前房型数据：", tableData.value);
  alert(JSON.stringify(tableData.value, null, 2));
  dialogVisible.value = false;
};

// 处理编辑
const handleEdit = row => {
  isEditing.value = true; // 进入编辑模式
  Object.assign(form.value, row); // 把当前行的数据赋值到表单
  editingOriginalId.value = row.typeId;
  dialogVisible.value = true; // 打开弹窗
};

// 处理提交（根据 isEditing 来判断是新增还是编辑）
const handleSubmit = async () => {
  // 先检查是否重复（仅限新增，或编辑时修改了 typeId）
  const isDuplicate = tableData.value.some(
    item =>
      item.typeId === form.value.typeId &&
      (!isEditing.value || item.typeId !== editingOriginalId.value)
  );
  if (isDuplicate) {
    ElMessage.error("类型ID不能重复！");
    return; // 如果重复，直接返回，不进行提交
  }
  try {
    if (isEditing.value) {
      // 编辑模式：调用后端API更新数据
      const response = await updateRoomType(form.value);
      if (response.code === 200) {
        // 更新成功后，更新对应表格数据，而非更新整个表格，性能更好
        const index = tableData.value.findIndex(
          item => item.typeId === editingOriginalId.value
        );
        if (index !== -1) {
          Object.assign(tableData.value[index], form.value);
        }
        ElMessage.success("修改成功");
      } else {
        ElMessage.error(response.msg || "修改失败");
        return;
      }
    } else {
      // 新增模式：调用后端API创建数据
      const response = await createRoomType(form.value);
      if (response.code === 200) {
        tableData.value.push({ ...form.value });
        ElMessage.success("创建成功");
      } else {
        ElMessage.error(response.msg || "创建失败");
        return;
      }
    }
    dialogVisible.value = false; // 关闭弹窗
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
};

const handleDelete = row => {
  console.log("正在删除: ", row);
  if (row) {
    ElMessageBox.confirm("确定要删除这个房型吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        try {
          const response = await deleteRoomType(row.typeId);
          if (response.code === 200) {
            // 删除成功后更新前端数据
            tableData.value = tableData.value.filter(
              item => item.typeId !== row.typeId
            );
            ElMessage.success("删除成功");
          } else {
            ElMessage.error(response.msg || "删除失败");
          }
        } catch (error) {
          console.error("删除失败:", error);
          ElMessage.error("删除失败，请稍后重试");
        }
      })
      .catch(() => {
        ElMessage.info("删除取消");
      });
  }
};
</script>

<style scoped>
/* 原样式内容保持不变 */
.room-type-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
